package cn.wolfcode.crud.web.controller;

import cn.wolfcode.crud.domain.Department;
import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.domain.Role;
import cn.wolfcode.crud.qo.EmployeeQuerObjcet;
import cn.wolfcode.crud.qo.JsonResult;
import cn.wolfcode.crud.qo.PageResult;
import cn.wolfcode.crud.qo.QuerObjcet;
import cn.wolfcode.crud.service.IDepartmentService;
import cn.wolfcode.crud.service.IEmployeeService;
import cn.wolfcode.crud.service.IRoleService;
import cn.wolfcode.crud.util.UserContext;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    protected IEmployeeService aemployee;
    @Autowired
    private IDepartmentService department;
    @Autowired
    protected IRoleService arole;

    //查询操作
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("eqo") EmployeeQuerObjcet eqo) {
        //把部门信息查询下来
        List<Department> departments = department.selectAll();
        model.addAttribute("PageResult", aemployee.query(eqo));
        model.addAttribute("departments", departments);
        return "employee/list";
    }

    //删除操作
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            aemployee.delete(id);
        }
        return "redirect:/employee/list";
    }

    //跳转页面
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        List<Role> roles = arole.selectAll();
        model.addAttribute("roles", roles);
        List<Department> departments = department.selectAll();
        model.addAttribute("departments", departments);
        if (id != null) {
            //这里是拿到所有的对象信息
            Employee employee = aemployee.get(id);
            model.addAttribute("employee", employee);
        }
        return "/employee/input";
    }

    //添加和修改
    @RequiresPermissions(value = {"employee:saveOrUpdate","员工添加"},logical = Logical.OR)
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {
        try {
            if (employee.getId() != null) {
                aemployee.update(employee, ids);
            } else {
                aemployee.insert(employee, ids);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false, "操作失败啦");
        }
    }
    @RequestMapping("/saveStatus")
    @ResponseBody
    public JsonResult saveStatus(long id,boolean status) {
        try {
            aemployee.saveStatus(id,status);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false, "操作失败啦");
        }
    }

    //修改密码功能跳转页面
    @RequestMapping("/inputupdatePwd")
    public String inputupdatePwd() {
        return "employee/updatePwd";
    }

    //修改密码功能
    @RequestMapping("/updatePwd")
    public String updatePwd(Model model, String oldPassword, String newPassword, HttpSession session) {
        Employee employee =(Employee) SecurityUtils.getSubject().getPrincipal();
        Md5Hash hash = new Md5Hash(oldPassword,employee.getName());
        if (!employee.getPassword().equals(hash.toString())) {
            model.addAttribute("str", "原密码错误");
            return "employee/updatePwd";
        }
        Md5Hash hash1 = new Md5Hash(newPassword,employee.getName());
        aemployee.updatePwd(hash1.toString(), employee.getId());
        return "redirect:/login.html";
    }
    //重置密码功能跳转页面
    @RequestMapping("/inputresetPwd")
    public String inputresetPwd(Long id, Model model) {
        Employee employee = aemployee.get(id);
        model.addAttribute("employee",employee);
        return "employee/resetPwd";
    }
    //重置密码功能
    @RequestMapping("/resetPwd")
    public String resetPwd( String newPassword, Long id){
        Employee employee = aemployee.get(id);
        Md5Hash hash1 = new Md5Hash(newPassword,employee.getName());
        aemployee.updatePwd(hash1.toString(), id);
        return "redirect:/employee/list";
    }
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids) {
        try {
            aemployee.batchDelete(ids);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败啦");
        }
    }
    @RequestMapping("/checkName")
    @ResponseBody
    //远程接收的一定是一对的才可以 valid:tuer
    public Map<String, Boolean> checkName(String name) {

            Employee employee=aemployee.checkName(name);
            Map<String, Boolean> map =new HashMap<>();
            map.put("valid",employee==null);
            return map;

    }
    //导入功能
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //写出一个文件
        Workbook wko =aemployee.exportXls();
        wko.write(response.getOutputStream());

    }
    //导入功能
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws Exception {//接收一个文件参数
        //直接读出来
        aemployee.importXls(file);
        return new JsonResult();
    }
}
